(function (window, $, undefined) {

    var Downloader = {};

	/**
	 * General utilities
	 */
	var Utils = {
		escapeQuotes: function(str){
			return typeof str == 'string' ? str.replace(/"/g, "&quot;").replace(/'/g, "&apos;") : str;
		}
	};

    /**
     * Represents a track in the DOM architecture, through its 'section-track' element
     */
    var TrackDOM = function (element) {
        this.sectionElement = element;
    };

    TrackDOM.isReady = function () {
        return trackList != undefined;
    };

    window.Downloader = Downloader;

    /**
     * Populates the songs list with a download link for each
     */
    Downloader.populateDownloadLinks = function () {
        if (!TrackDOM.isReady()) {
            return;
        }
        $('.section-track').each(function () {
            (new TrackDOM(this)).createDownloadLink();
        })
    };

    /**
     * Downloads the specified track object
     */
    Downloader.downloadTrack = function (track) {
        if (!track) {
            return alert("Invalid track!");
        }
        var r = $.ajax({url:'/serve/source/' + track.id + '/' + track.key, type:'get', async:false, cache:false, dataType:'json', error:function () {
            alert("It wasn't possible to download this track.")
        }});
    };

    TrackDOM.prototype = {

        /**
         * Creates the download link, if it doesn't yet exists, for the given item.
         */
        createDownloadLink:function () {
            if (this.hasDownloadLink()) {
                return;
            }
            var track = this.getTrack();
            if (!track) {
                return;
            }
			        var track_title = Utils.escapeQuotes(track.artist + (track.song ? ' - ' + track.song : ' - Unnamed'));
            var downloadControl = $("<a class='hm-download-ctrl' download='" + track_title + ".mp3' title='" + track_title + "' href='" + ('/serve/play/' + track.id + '/' + track.key) + "'>Download</a>");
            $(this.sectionElement).find('.play-ctrl').parent().append(downloadControl);
        },

        /**
         * Returns the ID for the track through its DOM
         */
        getId:function () {
            return this.sectionElement.id.replace('section-track-', '')
        },

        /**
         * Checks to see if the download link already exists
         */
        hasDownloadLink:function () {
            return $(this.sectionElement).find('.hm-download-ctrl').size() > 0
        },

        /**
         * Returns the hypem track element for this track DOM
         * This wrapper is used to avoid the truncation made on track.song
         */
        getTrack:function () {
            var track = trackList[document.location.href]['item_' + this.getId()];
            var domTitle = $(this.sectionElement).find('.track_name .base-title');
            var domRemixLink = $(this.sectionElement).find('.track_name .remix-link');
            var song = '';
            if (domTitle.size()){
                song = domTitle.text().trim();
                if (domRemixLink.size()){
                  song += ' ('+domRemixLink.text().trim()+')';
                }
                track.song = song;
            }
            return track;
        }

    };

    /**
     * From time to time, we plant a download link in each track
     */
    window.setInterval(Downloader.populateDownloadLinks, 2000);

})(window, jQuery);
